-module(tk_misc).
-include("common.hrl").

-export([compile/2]).
-export([start_applications/1,stop_applications/1]).
%% ====================================================================
%% API functions
%% ====================================================================
compile(Mod, RootDir) when is_atom(Mod) ->
	File = find_file(Mod, RootDir),
	compile:file(File, compile_options(RootDir)).

start_applications(Apps) ->
    manage_applications(fun lists:foldl/3,
        fun application:start/1,
        fun application:stop/1,
        already_started,
        cannot_start_application,
        Apps).

stop_applications(Apps) ->
    manage_applications(fun lists:foldr/3,
        fun application:stop/1,
        fun application:start/1,
        not_started,
        cannot_stop_application,
        Apps).

%%==============================LOCAL=======================================
compile_options(RootDir) ->
    EmakefileName = filename:join([RootDir, "Emakefile"]),
    {ok, [{_,CompileOptions}|_]} = file:consult(EmakefileName),
    lists:map(fun({i,Dir}) ->
        {i, filename:join([RootDir,Dir])};
        ({outdir,Dir}) ->
            {outdir, filename:join([RootDir, Dir])};
        (E) ->
            E
              end, CompileOptions).


find_file(Mod,Dir) ->
    FileName = atom_to_list(Mod)++".erl",
    filelib:fold_files(Dir, FileName, true, fun(E,_Acc) -> E end, undefined).

manage_applications(Iterate, Do, Undo, SkipError, ErrorTag, Apps) ->
    Iterate(fun (App, Acc) ->
        case Do(App) of
            ok -> [App | Acc];
            {error, {SkipError, _}} -> Acc;
            {error, Reason} ->
                lists:foreach(Undo, Acc),
                throw({error, {ErrorTag, App, Reason}})
        end
            end, [], Apps).
